<script setup>
import {
  ref,
  onMounted,
  onUnmounted,
  nextTick,
  watch,
  watchEffect,
  computed,
  reactive,
  toRefs,
  provide,
  h,
  createVNode,
} from "vue";
import { CloseOutlined } from "@ant-design/icons-vue";
import { nanoid } from "nanoid";
import request from "@/common/utils/request";
// 文案库组件
import CopyLibraryModal from "@/components/AddTextModal/CopyLibraryModal.vue";
// ai生成脚本
import AiCreateScript from "../Drawers/AiCreateScript.vue";
// 脚本库
import ScriptLibrary from "../Drawers/ScriptLibrary.vue";
// 风险词检测组件
import RiskWordDetection from "@/views/shotstack/MuseMixedCut/mixedCutCreat/components/riskWordDetecDrawer.vue";
import { message } from "ant-design-vue";
import store from "../../../../../../store";
import { useRouter, useRoute, onBeforeRouteLeave } from "vue-router";

const copyLibraryModalRef = ref(null);
const ScriptLibraryRef = ref(null);
const AiCreateScriptRef = ref(null);
const router = useRouter();
const route = useRoute();
const state = reactive({
  active: 1,
  // 脚本列表
  scriptArr: [
    {
      id: 1,
      content: "",
      isEdit: true,
      showCancel: false,
    },
  ],
});
onMounted(() => {
  state.scriptArr = route?.query?.sceneCreation
    ? store.state.shotstack.sceneCreationTexts.map((ele, index) => {
        return {
          id: index + 1,
          content: ele,
          isEdit: false,
          showCancel: false,
        };
      })
    : state.scriptArr;

  state.active = state.scriptArr[0].id;

  // 从文案仿写进入的
  if (route.query?.itemId && route.query?.imitation_id) {
    setImitationItem(route.query?.imitation_id);
  }
  console.log(route.query);
});

const setImitationItem = async (id) => {
  const res = await request.get(
    "/work_ai",
    `/user/shotstack/text/imitation/detail`,
    {
      id: +id,
    }
  );
  if (Array.isArray(route.query?.itemId)) {
    route.query.itemId.forEach((item, index) => {
      const find = res.result.result_content.find((ele) => ele.id == item);
      if (find) {
        if (index == 0) {
          state.scriptArr = [
            {
              id: find.id,
              content: find.subtitle_text_block.map((ele) => ele).join(","),
              isEdit: false,
              showCancel: false,
            },
          ];
          state.active = find.id;
        } else {
          state.scriptArr.push({
            id: find.id,
            content: find.subtitle_text_block.map((ele) => ele).join(","),
            isEdit: false,
            showCancel: false,
          });
        }
      }
    });
  } else {
    const find = res.result.result_content.find(
      (ele) => ele.id == route.query?.itemId
    );
    if (find) {
      state.scriptArr = [
        {
          id: find.id,
          content: find.subtitle_text_block.map((ele) => ele).join(","),
          isEdit: false,
          showCancel: false,
        },
      ];
      state.active = find.id;
      message.success("导入脚本成功!");
    }
  }

  console.log(res, "仿写详情");
};

// 脚本列表数量
const scriptArrLength = computed(() => {
  // 如果是正常的编辑, 返回脚本列表数量, 否则为初始创建的脚本, 去除默认脚本数量
  const someEdit = state.scriptArr.find((item) => item.isEdit);
  if (someEdit) {
    if (someEdit.content.trim() != "") {
      state.scriptArr.length;
    } else {
      return state.scriptArr.length - 1;
    }
  } else {
    return state.scriptArr.length;
  }
});

// 当前使用到的脚本以及id
const useScript = computed(() => {
  return state.scriptArr.map((ele) => {
    return {
      id: ele.id,
      content: ele.content,
    };
  });
});

// 脚本中使用

// 正在编辑的项
const editItem = computed({
  get() {
    const find = state.scriptArr.find((item) => item.id == state.active);
    return find || { content: "" };
  },

  set(val) {
    const find = state.scriptArr.find((item) => item.id == state.active);
    find.content = val;
  },
});

const cloneText = ref("");

// 修改编辑状态, 返回编辑的项
const changeEdit = (change = true) => {
  const find = state.scriptArr.find((item) => item.id == state.active);
  if (change) {
    find.isEdit = !find.isEdit;
    // 新增的项, 保存成功 恢复取消按钮的显示
    if (find?.showCancel == false && !find.isEdit) {
      find.showCancel = true;
    }
  }
  return find;
};

// 修改编辑状态 + 文字克隆保存
const changeEditState = () => {
  const find = changeEdit(true);
  // 复制保存
  cloneText.value = find.content;
};

// 重置文字
const resetText = () => {
  const find = changeEdit();
  find.content = cloneText.value;
  cloneText.value = false;
};

// 添加一个脚本组
const addScript = () => {
  if (state.scriptArr.length >= 5) return;
  const pushItem = {
    id: nanoid(),
    content: "",
    isEdit: true,
    showCancel: false,
  };
  state.scriptArr.push(pushItem);
  changeActive(pushItem.id);
};

// 删除一个脚本组
const delScriptItem = (data) => {
  state.scriptArr.splice(data.index, 1);
  if (state.active == data.id) {
    state.active = state.scriptArr[state.scriptArr.length - 1].id;
  }
};

// 修改当前高亮的脚本
const changeActive = (id) => {
  const find = changeEdit(false);
  state.active = id;

  if (find?.showCancel == false) return;
  find.isEdit = false;
};

// 打开ai生成脚本抽屉
const openScriptCreateDrawer = () => {
  AiCreateScriptRef.value.drawerControl.open();
};

// 打开文案库
const openScriptLibrary = () => {
  copyLibraryModalRef.value && copyLibraryModalRef.value.showModal();
};

// 脚本库选择了脚本
const selectScript = (list) => {
  if (state.scriptArr.length >= 5)
    return message.warning("当前脚本选择已达到上限5条");
  console.log(list, "选择的脚本");
  const pushArr = list.map((ele) => {
    return {
      id: ele?.submit_id || ele?.id || "selfCreat" + nanoid(),
      content: ele.content,
      isEdit: false,
    };
  });
  state.scriptArr.push(...pushArr);

  // 正在编辑, 并且是初始化的脚本(没有缓存文本)
  const findIndex = state.scriptArr.findIndex((ele) => ele.isEdit);

  if (findIndex != -1) {
    if (cloneText.value.trim() == "") {
      state.scriptArr.splice(findIndex, 1);
    } else {
      resetText();
    }
  }

  state.active = state.scriptArr[state.scriptArr.length - 1].id;

  console.log(state.scriptArr, "当前渲染的数组");
};

const script_tex = computed(() => {
  const filterItems = state.scriptArr.filter(
    (ele) => !ele.isEdit && ele.content && ele.content.trim()
  );
  if (!filterItems.length) return [];
  return filterItems.map((ele) => ele.content);
});
// 风险词检测
const riskWordDetection = ref(null);
const riskWordDetnHandle = () => {
  const find = state.scriptArr.find((item) => item.id == state.active);
  if (!find) {
    return message.warning("请输入脚本文案");
  } else {
    let text_arr = [];
    text_arr[0] = find.content;
    console.log(text_arr);
    riskWordDetection.value &&
      riskWordDetection.value.showDrawer(text_arr, "script_text");
  }
};

// 文案库选择文案回调
const closeChooseMaterial = async (data) => {
  console.log(data, "选择的文案");
  copyLibraryModalRef.value.closeModal();
  if (!Array.isArray(data) || (Array.isArray(data) && data.length == 0))
    return message.error("请选择文案");

  // 计算还能添加多少条文案，基于content是否为空
  const occupiedSlots = state.scriptArr.filter((item) => item.content).length;
  const remainingSlots = 5 - occupiedSlots;
  if (remainingSlots <= 0) {
    return message.warning("文案总数量已达到上限5条,无法再添加");
  }

  // 如果选择的文案数量大于剩余槽位数，则只添加剩余槽位数的文案
  const addCount = Math.min(data.length, remainingSlots);

  console.log(addCount, "还能加多少个槽位");

  // 将选择的文案转换为需要的格式，并根据addCount决定添加的数量
  const pushArr = data.slice(0, addCount).map((ele) => ({
    id: ele.submit_id || ele.id || "selfCreat" + nanoid(),
    content: ele.material_content,
    isEdit: false,
  }));

  // 将转换后的文案添加到state.scriptArr中
  state.scriptArr.push(...pushArr);

  // 给出添加成功的提示
  if (addCount < data.length) {
    message.warning(`文案总数量已达到上限5条,本次仅添加了${addCount}条`);
  }

  // 正在编辑, 并且是初始化的脚本(没有缓存文本)
  const findIndex = state.scriptArr.findIndex((ele) => ele.isEdit);

  // 检查添加后总数量是否超过5条

  if (findIndex != -1) {
    if (cloneText.value.trim() == "") {
      state.scriptArr.splice(findIndex, 1);
    } else {
      resetText();
    }
  }

  state.active = state.scriptArr[state.scriptArr.length - 1].id;

  console.log(state.scriptArr, "当前渲染的数组");
};

defineExpose({
  // 去除编辑状态的脚本
  script_tex,
  // 当前使用的脚本content 以及对应id 数组
  useScript,
});
</script>

<template>
  <div class="CustomScript">
    <div class="left_content_item">
      <!-- 分组标题 -->
      <span class="left_content_item_title">
        脚本文案
        <span class="red_dian"></span>
      </span>
      <!-- 每组的主要内容 -->
      <div class="left_content_item_main">
        <!-- 脚本抽屉卡片 -->
        <div class="script_cart_box">
          <div class="script_cart" @click="openScriptCreateDrawer">
            <div class="cart_msg_text">
              <p class="cart_title">AI生成文案</p>
              <span class="cart_desc">输入产品信息快捷生成文案并填充</span>
            </div>
          </div>
          <div class="script_cart script_library" @click="openScriptLibrary">
            <div class="cart_msg_text">
              <p class="cart_title">文案库</p>
              <span class="cart_desc">从历史生成保存的AI文案中选择并填充</span>
            </div>
          </div>
        </div>

        <!-- 脚本添加和编辑容器 -->
        <div class="script_edit_box">
          <!-- 头部 -->
          <div class="script_title_box">
            <div
              class="script_title_item"
              :class="{
                scriptActive: i.id === state.active,
              }"
              v-for="(i, index) in state.scriptArr"
              @click="changeActive(i.id)"
              :key="i.id"
            >
              脚本{{ index + 1 }}
              <a-popconfirm
                title="确定要删除吗？"
                ok-text="确认"
                cancel-text="取消"
                @confirm="
                  delScriptItem({
                    index,
                    id: i.id,
                  })
                "
              >
                <CloseOutlined
                  v-show="state.scriptArr.length > 1"
                  style="font-size: 11px"
                  @click.stop="() => {}"
                >
                </CloseOutlined>
              </a-popconfirm>
            </div>
            <a-button
              v-show="state.scriptArr.length < 5"
              type="link"
              :disabled="editItem.isEdit"
              style="padding: 0; line-height: 35px; margin-left: 15px"
              @click="addScript"
            >
              <span style="font-size: 16px; margin-right: 3px">+</span>
              添加</a-button
            >
          </div>

          <!-- 脚本编辑的部分 -->
          <div class="script_edit_content_box">
            <div class="script_edit_content_item">
              <div
                class="script_edit_content"
                :style="{
                  'border-bottom': editItem.isEdit
                    ? ''
                    : '1px solid rgb(202, 202, 202)',
                }"
              >
                <a-textarea
                  v-model:value="editItem.content"
                  show-count
                  :maxlength="600"
                  :autosize="{
                    minRows: 2,
                    maxRows: 8,
                  }"
                  placeholder="请输入脚本, 推荐“AI生成文案”或从文案库选择后填充"
                  v-if="editItem.isEdit"
                />
                <p class="else_p_element" v-else>
                  {{ editItem.content }}
                </p>
                <!-- <span class="script_from">脚本来源: AI脚本</span> -->
              </div>

              <div class="script_edit_content_footer">
                <a-space v-if="!editItem.isEdit">
                  <a-button
                    type="default"
                    size="small"
                    class="btn_style"
                    @click="changeEditState"
                  >
                    编辑
                  </a-button>
                  <a-button
                    type="default"
                    size="small"
                    class="btn_style"
                    @click="riskWordDetnHandle"
                  >
                    风险词检测
                  </a-button>
                </a-space>
                <div class="script_btn_box" v-else>
                  <a-button
                    type="primary"
                    size="small"
                    class="btn_style"
                    :disabled="!editItem?.content?.trim()"
                    @click="changeEdit(true)"
                  >
                    确认
                  </a-button>
                  <a-button
                    type="default"
                    size="small"
                    class="btn_style"
                    v-if="editItem?.showCancel != false"
                    @click="resetText"
                  >
                    取消
                  </a-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- ai生成脚本 -->
  <AiCreateScript
    ref="AiCreateScriptRef"
    :scriptArrLength="scriptArrLength"
    :useScript="useScript"
    @selectScript="selectScript"
  >
  </AiCreateScript>
  <!-- 脚本库 -->
  <!-- <ScriptLibrary
    ref="ScriptLibraryRef"
    :scriptArrLength="scriptArrLength"
    :useScript="useScript"
    @selectScript="selectScript"
  >
  </ScriptLibrary> -->
  <!-- @importSuccess="closeChooseMaterial" -->
  <!-- 文案库   -->
  <CopyLibraryModal
    ref="copyLibraryModalRef"
    selectType="checkbox"
    @importSuccess="closeChooseMaterial"
  />
  <RiskWordDetection ref="riskWordDetection" />
</template>

<style lang="less" scoped>
@bgc: #f4f4f5;

h3 {
  margin: 0;
}

.btn_style {
  padding: 0 15px;
  line-height: 24px;
}

// 小红点
.red_dian {
  display: inline-block;
  height: 4px;
  width: 4px;
  background: red;
  border-radius: 50%;
  overflow: hidden;
}

.CustomScript {
  .left_content_item {
    margin-bottom: 20px;

    // 分组标题 公共样式
    .left_content_item_title {
      display: flex;
      align-items: center;
      gap: 3px;
      margin-bottom: 15px;
      font-weight: 600;
    }

    // 分组内容 公共样式
    .left_content_item_main {
      // 打开抽屉的脚本卡片
      .script_cart_box {
        display: flex;
        gap: 15px;
        margin-bottom: 20px;

        .script_cart {
          flex: 1;
          // height: 92px;
          padding: 15px 12px;
          cursor: pointer;
          background-image: url("../../../imgs/script_ai.webp");
          background-repeat: no-repeat;
          background-size: contain;
          background-position: 175px center;
          background-size: 30%;
          background-color: #f0f8ff;
          border: 1px solid transparent;
          border-radius: 12px;
          transition: all 0.3s;

          &:hover {
            border-color: var(--ss-primary-color-hover);
          }

          .cart_msg_text {
            width: 50%;

            .cart_title {
              font-size: 14px;
              font-weight: 600;
              margin: 0;
            }

            .cart_desc {
              font-size: 12px;
              color: rgb(100, 102, 107);
            }
          }
        }

        .script_library {
          background-image: url("../../../imgs/script.webp");
          // background-image: url('../../../imgs/script-list-background-b0ca5754.png');
        }
      }

      // 脚本分组列表
      .script_edit_box {
        display: flex;
        flex-direction: column;

        // 脚本标题容器
        .script_title_box {
          display: flex;
          border: 1px solid rgb(230, 230, 230);
          border-radius: 8px 8px 0 0;

          .script_title_item {
            cursor: pointer;
            width: 85px;
            line-height: 35px;
            text-align: center;
            border-right: 1px solid rgb(230, 230, 230);

            &.scriptActive {
              color: var(--ss-primary-color);
              background: @bgc;
            }
          }
        }

        // 编辑内容容器
        .script_edit_content_box {
          .script_edit_content_item {
            padding: 15px;
            background: @bgc;

            .script_edit_content {
              .else_p_element {
                width: 100%;
                max-height: 186px;
                overflow-x: auto;
                overflow-y: auto;

                /* 确保宽度被限制 */
                &::-webkit-scrollbar {
                  width: 8px;
                  /* 滚动条的宽度 */
                  height: 10px;
                }

                &::-webkit-scrollbar-thumb {
                  /* 滑块的背景颜色 */
                  background: #a8a8a8;
                  /* 滑块的圆角 */
                  border-radius: 10px;
                }
              }

              .script_from {
                font-size: 12px;
              }
            }

            .script_edit_content_footer {
              margin-top: 10px;

              .script_btn_box {
                display: flex;
                gap: 10px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
